package com.cloud.tsp.config;

import com.cloud.core.exception.MyException;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author 杨斌
 * 2025-03-2025-03-20
 */
@Component
public class SmsCodeVerify {

    @Resource(name = "myRedis")
    private RedisTemplate<String, Object> redisTemplate;

    public void verifySmsCode(String phone, String code) {
        String redisCodeKey = "SERVICE_STATION:" + phone + ":code";
        String redisUsedKey = "SERVICE_STATION:" + phone + ":used";

        // 获取存储的验证码和使用状态
        String storedCode = (String) redisTemplate.opsForValue().get(redisCodeKey);
        String used = (String) redisTemplate.opsForValue().get(redisUsedKey);

        // 验证验证码是否为空
        if (code == null || code.trim().isEmpty()) {
            throw new MyException("wds.exception.verificationFailed");
        }

        // 验证验证码是否过期
        if (storedCode == null) {
            throw new MyException("wds.exception.verificationExpired");
        }

        // 验证验证码是否一致
        if (!storedCode.equals(code)) {
            throw new MyException("wds.exception.verificationError");
        }

        // 验证验证码是否已使用
        if ("true".equals(used)) {
            throw new MyException("wds.exception.verificationUsed");
        }

        // 验证码正确且未使用，标记为已使用
        redisTemplate.opsForValue().set(redisUsedKey, "true", Duration.ofMinutes(5));
    }
}
